package com.ceam.web.config;

import ma.glasnost.orika.Converter;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.util.Map;

/**
 * @author CeaM
 */
@Configuration
public class ConverterConfig {

    @Autowired
    private ApplicationContext context;

    @Bean
    public MapperFacade mapperFacade() {
        return mapperFactory().getMapperFacade();
    }
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MapperFactory mapperFactory() {
        DefaultMapperFactory factory = new DefaultMapperFactory.Builder().build();
        getConverters(factory);
        getMappers(factory);
        return factory;
    }

    @SuppressWarnings("unchecked")
    private void getConverters(DefaultMapperFactory factory) {
        Map<String, Converter> beansOfType = context.getBeansOfType(Converter.class);
        beansOfType.forEach((key, value) -> {
            factory.getConverterFactory()
                    .registerConverter(value);

        });
    }

    @SuppressWarnings("unchecked")
    private void getMappers(DefaultMapperFactory factory) {
        Map<String, Mapper> beansOfType = context.getBeansOfType(Mapper.class);
        beansOfType.forEach((key, value) -> {
            factory.registerMapper(value);
        });
    }

}
